import os
from PIL import Image

def resize_image(input_path, output_path, max_width=1000):
    """按比例缩放图片，最大宽度为max_width"""
    try:
        with Image.open(input_path) as img:
            # 计算缩放比例
            if img.width > max_width:
                ratio = max_width / img.width
                new_height = int(img.height * ratio)
                # 使用高质量的LANCZOS重采样滤波器
                img = img.resize((max_width, new_height), Image.LANCZOS)
            
            # 确保输出目录存在
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            
            # 保存图片，保持原有质量
            img.save(output_path, quality=95)
            print(f"已处理: {input_path} -> {output_path}")
    except Exception as e:
        print(f"处理 {input_path} 时出错: {e}")

def process_specific_directories(main_dir, target_dirs, output_root):
    """处理指定的子目录"""
    for dir_name in target_dirs:
        input_dir = os.path.join(main_dir, dir_name)
        if not os.path.exists(input_dir):
            print(f"目录不存在: {input_dir}，跳过")
            continue
            
        print(f"正在处理目录: {input_dir}")
        
        # 遍历目录中的所有文件
        for root, _, files in os.walk(input_dir):
            for file in files:
                if file.lower().endswith(('.jpg', '.jpeg')):
                    input_path = os.path.join(root, file)
                    # 构建输出路径
                    relative_path = os.path.relpath(root, main_dir)
                    output_dir = os.path.join(output_root, relative_path)
                    output_path = os.path.join(output_dir, file)
                    
                    resize_image(input_path, output_path)

if __name__ == "__main__":
    # 设置主目录为当前目录
    main_directory = os.getcwd()
    
    # 指定要处理的子目录
    target_directories = [
    		"Python语言程序设计",
    		"Web程序设计",
    		"数据库原理"
	]
    
    # 输出目录为当前目录下的"converted"文件夹
    output_directory = os.path.join(main_directory, "converted")
    
    print(f"主目录: {main_directory}")
    print(f"目标子目录: {target_directories}")
    print(f"输出目录: {output_directory}")
    
    process_specific_directories(main_directory, target_directories, output_directory)
    
    print("指定目录的图片处理完成!")